<!--hmc 发放优惠券组件-->
<template>
  <div class="container">
    <p class="font20 color333">执行动作-发放优惠券</p>
    <div class="stepset mb30">
      <ul>
        <li :class="{'active':active>=1}">
          <span>1</span>
          <p>选择优惠券</p>
        </li>
        <li :class="{'active':active>=2}">
          <span>2</span>
          <p>选择触达方式</p>
        </li>
      </ul>
    </div>
    <div v-show="active==1">
      <el-form :inline="true" :model="tablePagination" size="mini" ref="tablePagination">
        <el-form-item label="优惠券活动ID：" prop="promotionId" class="mb20 noMarginRight">
          <el-input clearable v-model="tablePagination.promotionId" placeholder="输入优惠券活动ID" maxlength="80" size="mini" class="w194"/>
        </el-form-item>
        <el-form-item label="优惠券活动：" prop="promName" class="mb20 noMarginRight">
          <el-input clearable v-model="tablePagination.promName" placeholder="输入优惠券活动名称" maxlength="80" size="mini" class="w194" />
        </el-form-item>
        <el-form-item class="mb20 noMarginRight">
          <el-button class="resetButton" icon="el-icon-refresh" @click="restForm">重置</el-button>
          <el-button class="searchButton" @click="searchCoupon" icon="el-icon-search">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" v-loading = "loading" class="mb20">
        <el-table-column align="center" label="活动ID" width="280px">
          <template slot-scope="scope">
            <el-radio v-model="values" :label="scope.row.promotionId" @change.native="selectCoupon(scope.row)"></el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="活动ID" prop="promotionId"></el-table-column> -->
        <el-table-column align="center" label="活动名称" prop="promName"></el-table-column>
        <el-table-column align="center" label="活动时间">
          <template slot-scope="scope">
              {{scope.row.startTime}} - {{scope.row.endTime}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="有效期">
          <template slot-scope="scope">
              {{scope.row.couponUseStartTime}} - {{scope.row.couponUseEndTime}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="当前状态">
          <template slot-scope="scope">
              <span v-if="scope.row.status == 9">活动草稿</span>
              <span v-else-if="statusFormat(scope.row) == 11">待提交</span>
              <span v-else-if="statusFormat(scope.row) == 12">待审核</span>
              <span v-else-if="statusFormat(scope.row) == 13">未开始</span>
              <span v-else-if="statusFormat(scope.row) == 14">审核未通过</span>
              <span v-else-if="statusFormat(scope.row) == 15">进行中</span>
              <span v-else-if="statusFormat(scope.row) == 16">已过期</span>
              <span v-else-if="statusFormat(scope.row) == 17">已结束</span>
              <span v-else-if="scope.row.status == 7">已关闭</span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" v-if="promotionId != scope.row.promotionId" @click="selectCoupon(scope.row)">选择</el-button>
            <el-button type="text" v-else disabled>已选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页栏-->
      <div class="toolbar t_r mb60" v-if="tableData.length > 0">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="tablePagination.start"
          :page-size="tablePagination.limit"
          :total="tableTotal"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>

    <div v-show="active==2">
      <div class="flex mt30 mb40">
        <span class="font16 color333 turnInlineBlock lh40 h40">选择触达方式：</span>
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="短信" border ></el-checkbox>
          <el-checkbox label="邮件" border ></el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="tab-container ">
        <el-tabs v-model="activeName" ref="tabs">
          <el-tab-pane v-for="item in tabList" :key="item.key" :label="item.label" :name="item.key"></el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="activeName=='0' && checkList.indexOf('短信') != -1">
        <el-form :model="ruleForm" size="mini" ref="ruleForm" :rules="rules">
          <el-form-item label="短信模板：" prop="smsSelect" class="mb30">
            <el-select v-model="ruleForm.smsSelect" filterable placeholder="选择短信模板" size="mini"  @change="onChange" class="w495 mr20 turnBlock f_l" >
              <el-option
                v-for="item in smsList"
                :key="item.thirdTemplateId"
                :label="item.templateName"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button  class="cancelButton mr20 turnBlock f_l"  @click="tTempalteListAll">刷新</el-button>
            <el-button  class="searchButton noMarginLeft turnBlock f_l"  @click="addTemplateLink">模板管理</el-button>
          </el-form-item>
          <el-form-item label="可选参数：" class="mb30" label-width="91px">
            <el-button type="primary" icon="el-icon-document-copy" v-clipboard:copy="promName"
            v-clipboard:success="onCopy" class="copyBtn mr20" v-clipboard:error="onError">活动名称</el-button>
            <el-button type="primary" icon="el-icon-document-copy" v-clipboard:copy="chineseDesc"
            v-clipboard:success="onCopy" class="copyBtn mr10" v-clipboard:error="onError">活动描述</el-button>
            <span class="desc">*操作说明：点击复制相关参数，可粘贴至内容中</span>
          </el-form-item>
          <el-form-item label="短信内容：" :required="true" class=" mb30 txt">
            <el-input type="textarea" class="w706 flex" v-html="smsContent"></el-input>
          </el-form-item>
          <el-form-item label="测试发送：" class=" flex phone labelMarginLeft5 mb60" >
            <el-input clearable v-model.number="sendCouponDataForm.smsJson.testPhone" maxlength="11" placeholder="输入测试发送手机号" class="w495 mr20"></el-input>
            <el-button  @click="sendTestMessage(1)" class="searchButton">发送</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="activeName=='1' && checkList.indexOf('邮件') != -1">
        <el-form :model="ruleForm" size="mini" ref="ruleForm" :rules="rules">
          <el-form-item label="邮件模板：" prop="emailSelect" class=" mb30">
            <el-select v-model="ruleForm.emailSelect" filterable placeholder="选择邮件模板"  size="mini" @change="templateSelectMail"  class="w605 mr20 turnBlock f_l">
              <el-option
                v-for="item in emailList"
                :key="item.thirdTemplateId"
                :label="item.templateName"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button  class="cancelButton mr20 turnBlock f_l" @click="tTempalteListAll">刷新</el-button>
            <el-button class="searchButton noMarginLeft turnBlock f_l" @click="addTemplateLink">模板管理</el-button>
          </el-form-item>
          <el-form-item label="可选参数：" class="mb30" label-width="91px" >
            <el-button icon="el-icon-document-copy" v-clipboard:copy="promName"
            v-clipboard:success="onCopy" class="copyBtn mr20" v-clipboard:error="onError">活动名称</el-button>
            <el-button icon="el-icon-document-copy" v-clipboard:copy="chineseDesc"
            v-clipboard:success="onCopy" class="copyBtn mr20" v-clipboard:error="onError">活动描述</el-button>
            <span class="desc">*操作说明：点击复制相关参数，可粘贴至内容中</span>
          </el-form-item>
          <el-form-item label="邮件标题：" prop="sendCouponDataForm.mailJson.title" class="mb30">
            <el-input clearable v-model="sendCouponDataForm.mailJson.title" placeholder="请输入邮件标题" maxlength="80" class="w605"></el-input>
          </el-form-item>
          <el-form-item label="邮件内容：" class=" mb30 txt" :required="true">
            <div class="w706 flex mr20 f_l"   v-html="mailContent"></div>
            <el-button class="searchButton turnBlock f_l" @click="preview()" >预览</el-button>
          </el-form-item>
          <!-- <el-form-item class="w178 mt30 txt">

          </el-form-item> -->
          <el-form-item label="测试发送：" class="mb60 flex phone labelMarginLeft5" >
            <el-input clearable v-model="sendCouponDataForm.mailJson.testMail" placeholder="输入测试邮箱" class="w738 mr20"></el-input>
            <el-button class="searchButton" @click="sendTestMessage(3)">发送</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="save t_c ">
      <el-button v-if="active == 1" @click="changeDialog" class="cancelButton mr60">取消</el-button>
      <el-button v-if="active == 1" @click="next" class="searchButton">下一步</el-button>
      <el-button v-if="active == 2" @click="active=1" class="cancelButton mr60">上一步</el-button>
      <el-button v-if="active == 2" @click="saveInfo" class="searchButton">确认</el-button>
    </div>

    <el-dialog title="编辑"  :visible.sync="editorDialogVisible" :close-on-click-modal="false" width="50%" center append-to-body>
      <el-form :model="mailParamsForm" size="mini" ref="mailParamsForm">
        <el-upload class="avatar-uploader" :action="imgUpload" multiple :on-success="uploadSuccess" :show-file-list="false"></el-upload>
        <el-form-item label="编辑内容：" prop="params" label-width="100px" style="margin-top: 2px;" required>
          <quill-editor ref="sendGoodsEditor" v-model="mailParamsForm.params" style="height: 300px;margin-bottom: 45px;margin-top: 10px;" :options="editorOption"></quill-editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorDialogVisible = false" class="cancelButton mr60">取 消</el-button>
        <el-button type="primary" @click="confirmParams" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="预览" :close-on-click-modal="false" :visible.sync="previewDialogVisible" width="50%" center append-to-body>
      <div>
        <h2 style="text-align: center; margin-top: 10px;">{{sendCouponDataForm.mailJson.title}}</h2>
        <div style="margin: 10px 30px 30px 30px;" v-html="this.previewContent"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false" class="searchButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 自动化营销-----发放优惠券组件
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { isEmail,isMobile } from "@/utils/validate";

//富文本工具栏
var toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  ['link', 'image'],
  [{ 'align': [] }],

  ['clean']                                         // remove formatting button
];

export default {
  name: "sendCoupon",
  components: {quillEditor},
  props: {
    nodeInfo: {
      type: Object,
    },
    journeyId: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      imgUpload: this.utils.imghost,
      editorOption: {
        theme: 'snow',
        boundary: document.body,
        modules: {
          toolbar: {
            container: toolbarOptions,//工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          },
        },
        placeholder: '请输入参数内容',
        readOnly: false
      }, // 富文本初始化
      tableData: [],
      checkList: ["短信", "邮件"],
      active: 1, //初始选中
      activeName: 0,
      tabList: [
        { label: "短信", key: "0" },
        { label: "邮件", key: "1" }
      ],
      //表单规则
      ruleForm: {
        smsSelect: null,
        emailSelect: null,
      },
      //下拉
      smsList:[],
      emailList: [],
      //select 值
      value: "",
      //form规则
      rules: {
        smsSelect: [
          { required: true, message: "请选择短信模板", trigger: "change" }
        ],
        emailSelect: [
          { required: true, message: "请选择邮件模板", trigger: "change" }
        ],
        sendCouponDataForm:{
          mailJson:{
            title: [
              { required: true, message: "请输入邮件标题", trigger: "blur" }
            ],
          }
        }
      },
      //短信内容
      textarea: "",
      //翻页
      tablePagination: {
        start: 1,
        limit: 10,
        promType: 11
      },
      //已选择的活动Id
      promotionId: null,
      promName : null,
      chineseDesc: null,
      loading : false,
      sendCouponDataForm:{
        smsJson:{
          params:{

          },
          testPhone: ""
        },
        mailJson:{
          title:"",
          params:{

          },
          testMail:""
        },
      },
      //短信模版内容
      smsContent: "",
      smsParams:[],
      //邮件模版内容
      mailContent: "",
      mailParams:[],
      mailParamsForm:{
        params:'',
        key:'', // 参数名称
      },
      editorDialogVisible: false,
      previewContent:"",
      previewDialogVisible: false,//邮件预览弹窗
      templateContent: "",

      startTime: null,
      endTime: null,
      couponStartTime: null,
      couponEndTime: null,
      smsTemplateContent: null, //短信模板内容
      values : null ,
      smsParamFlag:null,
    };
  },

  methods: {
    /**
     * 富文本图片上传
     */
    uploadSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.sendGoodsEditor.quill
      // 上传成功所执行
      if (res.code == "0000" && res.data !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, 'image',res.data.imageUrl)
        // 光标移动至文本末端
        quill.setSelection(length + 1)
      } else {
        this.$message({message:"图片插入失败", type:"error" });
      }
    },
    /**
     * 模板模糊搜索
     */
    smsRemoteMethod(query){
      this.utils.request.tTempalteListAll({status: 1, templateType: 1, templateName: query},res=>{
          if(res.code == '0000'){
            this.smsList = res.data
          }else{
            this.smsList = []
          }
      })
    },
    /**
     * 模板模糊搜索
     */
    emailRemoteMethod(query){
      this.utils.request.tTempalteListAll({status: 1, templateType: 2, templateName: query},res=>{
          if(res.code == '0000'){
            this.emailList = res.data
          }else{
            this.emailList = []
          }
      })
    },
    /**
     * 邮件预览
     */
    preview(){
      if(this.sendCouponDataForm.mailJson.tempId =="" || this.sendCouponDataForm.mailJson.tempId == null){
        this.$message({message:"请选择邮件模版输入参数后预览",type:"error"})
        return false;
      }
      // if(this.sendCouponDataForm.mailJson.title == null || this.sendCouponDataForm.mailJson.title == ''){
      //   this.$message({message:"请输入邮件模板标题",type:"error"})
      //   return false;
      // }
      //判断参数是否全部输入
      var booFlag = false;
      for (const key in this.sendCouponDataForm.mailJson.params) {
        const value = this.sendCouponDataForm.mailJson.params[key];
        if(value == null ||  value == ''){
            booFlag = true;
            break;
        }
      }
      if(booFlag){
        this.$message({message:"请补充完参数后预览",type:"error"})
        return false;
      }
      //预览数据组装
      var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
      if(paramList == null){
        this.previewDialogVisible = true;
        return false;
      }
      var content = this.templateContent;
      for(var i=0;i<paramList.length;i++){
        var key = paramList[i].replace("${","").replace("}","");
        content= content.replace(paramList[i],this.sendCouponDataForm.mailJson.params[key]);
      }
      this.previewContent = content;
      this.previewContent = this.previewContent.replace(/img/g,"img style='width:100%;height:100%'"); 
      this.previewDialogVisible = true;

    },
    /**
     * 重置
     */
    restForm(){
      let keys = ["promotionId","promName"]
      //调用校验
      let  boo = this.seachTableUtils.checkFromIsNull(this.tablePagination,keys)
      if(!boo){
        return;
      }
      this.$set(this.tablePagination, "start", 1)
      this.$set(this.tablePagination, "limit", 10)
      this.$set(this.tablePagination, "promotionId", null);
      this.$set(this.tablePagination, "promName", null);
      this.getCouponList();
    },
    /**
     * 状态格式化
     */
    statusFormat(row) {
      if (
        row.status == 1 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //待提交
        return 11;
      } else if (
        row.status == 2 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //待审核
        return 12;
      } else if (
        row.status == 11 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //未开始
        return 13;
      } else if (
        row.status == 4 &&
        new Date().getTime() <= new Date(row.startTime).getTime()
      ) {
        //审核未通过
        return 14;
      } else if (
        row.status == 11 &&
        new Date().getTime() >= new Date(row.startTime).getTime() &&
        new Date().getTime() <= new Date(row.endTime).getTime()
      ) {
        //进行中
        return 15;
      } else if (
        (row.status == 1 || row.status == 2 || row.status == 4) &&
        new Date().getTime() > new Date(row.startTime).getTime()
      ) {
        //已过期
        return 16;
      } else if (
        row.status == 11 &&
        new Date().getTime() > new Date(row.endTime).getTime()
      ) {
        //已结束
        return 17;
      }
    },
    //换页刷新
    refreshPageRequest(val){
        this.tablePagination.start = val;
        this.getCouponList();
    },
    //子关闭 标签选择弹框
    changeDialog() {
      this.$emit("changeCouponDlg", false);
    },
    searchCoupon(){
      this.tablePagination.start = 1;
      this.getCouponList();
    },
    getCouponList(){
      /**
       * 查询优惠券List
       */
      this.loading = true;
      this.utils.request.getCouponList(this.tablePagination,res=>{
        this.loading = false;
          if(res.code == '0000'){
            this.tableData = res.data.rows;
            this.tableTotal = Number(res.data.total);
          }
      })
    },
    selectCoupon(row){
        this.promotionId = row.promotionId;
        this.values = row.promotionId;
        this.promName = row.promName;
        this.chineseDesc = row.chineseDesc;
        this.startTime = row.startTime;
        this.endTime = row.endTime;
        this.couponStartTime = row.couponUseStartTime;
        this.couponEndTime = row.couponUseEndTime;
    },
    next(){
      if(this.promotionId == null || this.promotionId == ''){
        this.$message({
          type:"warning",
          message:"请选择优惠券活动"
        })
      }else{
        this.active = 2;
      }
    },
    // 复制成功
    onCopy(e){
      //复制成功后获取输入框光标赋值
      if(this.smsParamFlag && this.smsParamFlag != null && e.text ){
        var myField = document.getElementById(this.smsParamFlag);
        var myValue = e.text;
        if (myField.selectionStart || myField.selectionStart == '0') {
          var startPos = myField.selectionStart;
          var endPos = myField.selectionEnd;
          // save scrollTop before insert
          var restoreTop = myField.scrollTop;
          myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
          if (restoreTop > 0) {
          // restore previous scrollTop
          myField.scrollTop = restoreTop;
          }
          myField.focus();
          myField.selectionStart = startPos + myValue.length;
          myField.selectionEnd = startPos + myValue.length;
          }
        else {
          myField.value += myValue;
          myField.focus();
        }
        //document.getElementById(this.smsParamFlag).value = e.text;;
      }else{
        this.smsParamFlag = null;
      }
      this.$message({
        type: "success",
        message: "复制成功"
      })
    },
    // 复制失败
    onError(e){
      this.$message({
        type: "error",
        message: "复制失败"
      })
    },
    /**
     * 查询短信邮件模板
     */
    tTempalteListAll(){
      //查询短信
      this.utils.request.tTempalteListAll({status: 1, templateType: 1},res=>{
          if(res.code == '0000'){
            this.smsList = res.data
          }else{
            this.smsList = []
          }

          //查询邮件
          this.utils.request.tTempalteListAll({status: 1, templateType: 2},res=>{
              if(res.code == '0000'){
                this.emailList = res.data
              }else{
                this.emailList = []
              }

              // 查询是否存在变量
              this.queryInfo();
          })
      })

    },
    onChange(val){
      let item = null;
      this.smsParamFlag = null;//清空短信模板动态标识
      this.smsList.forEach(sms=>{
        if(sms.id == val){
          // this.smsInfo = sms;
          item = sms;
        }
      })
      if(this.smsInfo == null){
        this.emailList.forEach(email=>{
          if(val == email.id){
            // this.emailInfo = email;
            item = email;
          }
        })
      }
      if(item == null){
          this.$message({
            type:"error",
            message: "模板不存在"
          })
          return false;
      }
      // let value = item.templateContent;
      var content = item.templateContent;

      this.smsTemplateContent = item.templateContent;
      var textList = content.split(/\$\{[^}]+\}/);
      var paramList = content.match(/\$\{[^}]+\}/g);
      this.smsParams = [];
      this.sendCouponDataForm.smsJson.params = {};

      this.sendCouponDataForm.smsJson.tempId = item.thirdTemplateId;
      this.sendCouponDataForm.smsJson.templateName = item.templateName;
      this.sendCouponDataForm.smsJson.id = item.id;

      if(paramList == null){
        this.smsContent = content;
        return;
      }

      for(var i=0;i<paramList.length;i++){
        this.smsParams.push(paramList[i].replace("${","").replace("}",""));
        this.sendCouponDataForm.smsJson.params[paramList[i].replace("${","").replace("}","")] = "";
        content= content.replace(paramList[i],'&nbsp;&nbsp;<textarea class="textareaParm" type="text"  id="'+paramList[i].replace("${","").replace("}","")+'"></textarea>&nbsp;&nbsp;');
      }
      this.smsContent = content;
      var that = this;
      //短信模板动态增加onfocus事件
      $(document).ready(function(){
          $(function() {
            for(var i=0;i<paramList.length;i++){
              let j = i;
              let key = paramList[j].replace("${","").replace("}","");
              document.getElementById(key).onfocus = function(){
                that.smsParamFlag = key;
              }
            }
          });

      })
    },
    /**
     * 测试发送
     */
    sendTestMessage(type){
      let that = this;
      let params = {
        type: type,
      }
      if( type == 1 ){
        if(that.sendCouponDataForm.smsJson == null || that.sendCouponDataForm.smsJson.tempId == null ||  that.sendCouponDataForm.smsJson.tempId == ''){
          that.$message({message:"请选择短信模板", type: "error"});
          return false;
        }
        if( type == 1 && (that.sendCouponDataForm.smsJson.testPhone == null || that.sendCouponDataForm.smsJson.testPhone == '')){
          that.$message({message:"请输入测试手机号", type: "error"})
          return false;
        }
        if(!isMobile(that.sendCouponDataForm.smsJson.testPhone)){
          this.$message({message:"请输入正确的手机号", type:"error"});
          that.sendCouponDataForm.smsJson.testPhone = "";
          return false;
        }
        if(that.smsParams.length > 0){
          for(var i=0;i<that.smsParams.length;i++){
            var key = that.smsParams[i];
            this.sendCouponDataForm.smsJson.params[key] = document.getElementById(key).value;
            if(this.sendCouponDataForm.smsJson.params[key]==null || this.sendCouponDataForm.smsJson.params[key]=='' ){
              that.$message({ message: "请补全短信内容参数", type: "error" });
              return false;
            }
          }
        }
        params = Object.assign(params, this.sendCouponDataForm.smsJson);
        params.testReceiver = this.sendCouponDataForm.smsJson.testPhone
      }else if( type == 3 ){
        if(that.sendCouponDataForm.mailJson == null || that.sendCouponDataForm.mailJson.tempId == null ||  that.sendCouponDataForm.mailJson.tempId == ''){
          that.$message({message:"请选择邮件模板", type: "error"});
          return false;
        }

        if( type == 1 && (that.sendCouponDataForm.mailJson.testMail==null || that.sendCouponDataForm.mailJson.testMail == '')){
          that.$message({message:"请输入测试邮箱", type: "error"})
          return false;
        }
        if(!isEmail(that.sendCouponDataForm.mailJson.testMail)){
          that.$message({message:"请输入正确的邮箱", type:"error"});
          that.sendCouponDataForm.mailJson.testMail = "";
          return false;
        }
        if(that.mailParams.length > 0){
          for(var i=0;i<that.mailParams.length;i++){
            var key = that.mailParams[i];
            if(this.sendCouponDataForm.mailJson.params[key]==null || this.sendCouponDataForm.mailJson.params[key]=='' ){
              that.$message({ message: "请补全邮件参数", type: "error" });
              return false;
            }
          }
        }

        if(that.sendCouponDataForm.mailJson.title ==null || that.sendCouponDataForm.mailJson.title == ''){
          that.$message({message:"请输入邮件标题", type: "error"})
          return false;
        }

        params = Object.assign(params, this.sendCouponDataForm.mailJson);
        params.testReceiver = this.sendCouponDataForm.mailJson.testMail;
      }
      this.utils.request.sendTestMessage(params, res => {
        if (res.code == "0000") {
          if(res.data.code == "0"){
            that.$message({ message: res.data.message, type: "success" });
          }else{
            that.$message({ message: res.data.message, type: "error" });
          }
        }
      });
    },

    /**
     * 邮件模版选择
     */
    templateSelectMail(val){
      let item = null;
      this.smsList.forEach(sms=>{
        if(sms.id == val){
          // this.smsInfo = sms;
          item = sms;
        }
      })
      if(this.smsInfo == null){
        this.emailList.forEach(email=>{
          if(val == email.id){
            // this.emailInfo = email;
            item = email;
          }
        })
      }
      if(item == null){
          this.$message({
            type:"error",
            message: "模板不存在"
          })
          return false;
      }
      var content = item.templateContent;
      this.previewContent = item.templateContent;
      this.templateContent = item.templateContent;
      var textList = content.split(/\$\{[^}]+\}/);
      var paramList = content.match(/\$\{[^}]+\}/g);
      this.mailParams = [];
      this.sendCouponDataForm.mailJson.params = {};
      if(paramList == null){
          this.mailContent = content;
          return;
      }
      for(var i=0;i<paramList.length;i++){
        this.mailParams.push(paramList[i].replace("${","").replace("}",""));
        this.sendCouponDataForm.mailJson.params[paramList[i].replace("${","").replace("}","")] = "";
        content= content.replace(paramList[i],'&nbsp;&nbsp;<button class="buttonParm" type="button" onsubmit="return false" id="'+paramList[i].replace("${","").replace("}","")+i+'">编辑</button>&nbsp;&nbsp;');
      }
      this.sendCouponDataForm.mailJson.tempId = item.thirdTemplateId;
      this.sendCouponDataForm.mailJson.title = item.templateTitle;
      this.sendCouponDataForm.mailJson.templateName = item.templateName;
      this.sendCouponDataForm.mailJson.id = item.id;
      this.mailContent = content;
      var mailParamsList = this.mailParams;
      //绑定按钮事件
      var that = this;
      $(document).ready(function(){
          $(function() {
            //jq事件
            for(var i=0;i<mailParamsList.length;i++){
              let j = i;
              let key = mailParamsList[j];
              document.getElementById(key+j).onclick = function(){
                that.editorDialogVisible = true;
                that.mailParamsForm.key = key;
                //设置value
                that.mailParamsForm.params = that.sendCouponDataForm.mailJson.params[key]
              }
            }
          });

      })
    },

    confirmParams(){
      if(this.mailParamsForm.params == null || this.mailParamsForm.params == '' ){
        this.$message({message:"请输入内容", type:"error" });
        return false;
      }
      var key = this.mailParamsForm.key;
      this.sendCouponDataForm.mailJson.params[key] = this.mailParamsForm.params;
      this.editorDialogVisible = false;
    },
    /**
     * 保存
     */
    saveInfo(){
      //判断必填项
      if(this.checkList.length < 1){
        this.$message({"type":"warning",message:"请选择触达方式"})
        return false;
      }

      let reachType = [];
      if(this.checkList.indexOf("短信") != -1){
         reachType.push('1');
      }
      if(this.checkList.indexOf("邮件") != -1){
        reachType.push("3")
      }

      let saveParams = {
        promotionId : this.promotionId,
        promName : this.promName,
        chineseDesc : this.chineseDesc,
        startTime: this.startTime,
        endTime: this.endTime,
        couponStartTime: this.couponStartTime,
        couponEndTime: this.couponEndTime,
        reachType : reachType.join(",")
      };
      if(this.checkList.indexOf("短信") != -1){

        if(this.sendCouponDataForm.smsJson.tempId =="" || this.sendCouponDataForm.smsJson.tempId == null){
          this.$message({message:"请选择短信模版并输入参数后保存",type:"error"})
          return false;
        }
        //选择短信 组装短信内容
        for(var i=0;i<this.smsParams.length;i++){
          var key = this.smsParams[i];
          this.sendCouponDataForm.smsJson.params[key] = document.getElementById(key).value;
          if(this.sendCouponDataForm.smsJson.params[key]==null || this.sendCouponDataForm.smsJson.params[key]=='' ){
            this.$message({ message: "请补全短信内容参数后保存", type: "error" });
            return false;
          }
        }


        //短信预览数据组装
        var paramList = this.smsTemplateContent.match(/\$\{[^}]+\}/g);
        var content = this.smsTemplateContent;
        if(paramList != null && paramList.length > 0){
          for(var i=0;i<paramList.length;i++){
            var key = paramList[i].replace("${","").replace("}","");
            content= content.replace(paramList[i],this.sendCouponDataForm.smsJson.params[key]);
          }
        }
        this.sendCouponDataForm.smsJson.previewContent = content;

        this.sendCouponDataForm.smsJson.type = 1;
        this.sendCouponDataForm.smsJson.testPhone='';
        saveParams.smsJson = this.sendCouponDataForm.smsJson
      }
      if(this.checkList.indexOf("邮件") != -1){
        //选择邮件 组装邮件内容
        if(this.sendCouponDataForm.mailJson.tempId =="" || this.sendCouponDataForm.mailJson.tempId == null){
          this.$message({message:"请选择邮件模版并输入参数后保存",type:"error"})
          return false;
        }
        if(this.sendCouponDataForm.mailJson.title == null || this.sendCouponDataForm.mailJson.title == ''){
          this.$message({message:"请输入邮件模板标题",type:"error"})
          return false;
        }
        //判断参数是否全部输入
        var booFlag = false;
        for (const key in this.sendCouponDataForm.mailJson.params) {
          const value = this.sendCouponDataForm.mailJson.params[key];
          if(value == null ||  value == ''){
              booFlag = true;
              break;
          }
        }
        if(booFlag){
          this.$message({message:"请补充完邮件参数后保存",type:"error"})
          return false;
        }
        //邮件预览数据组装
        var paramList = this.templateContent.match(/\$\{[^}]+\}/g);
        var content = this.templateContent;
        if(paramList != null && paramList.length > 0){
          for(var i=0;i<paramList.length;i++){
            var key = paramList[i].replace("${","").replace("}","");
            content= content.replace(paramList[i],this.sendCouponDataForm.mailJson.params[key]);

          }
        }
        this.sendCouponDataForm.mailJson.previewContent = content;
        saveParams.mailJson = this.sendCouponDataForm.mailJson
        saveParams.mailJson.testMail = '';
      }
      this.utils.request.updateBranchNode({id: this.nodeInfo.nodeId, nodeVariable: JSON.stringify(saveParams)},res=>{
        if(res.code == '0000'){
          this.$emit("saveLabelData",{"nodeName": this.promName})
          this.$message({type:"success",message:"设置成功"})
          this.$emit("changeCouponDlg", false);
        }
      })
    },
    queryInfo(){
        this.utils.request.getBranchNodeDetail({branchNodeId: this.nodeInfo.nodeId}, res=>{
          if(res.code == '0000'){
            if(res.data.nodeVariable != null || res.data.nodeVariable != ''){
                //回显数据
                let data = JSON.parse(res.data.nodeVariable);
                this.promotionId = data.promotionId;
                this.values = data.promotionId;
                this.promName = data.promName;
                this.chineseDesc = data.chineseDesc;

                this.checkList = [];
                //回显reachType
                let reachType = data.reachType.split(",");
                if(reachType.indexOf("1") != -1){
                  //回显短信
                  this.checkList.push("短信")
                  // this.sendCouponDataForm.smsJson = data.smsJson;
                  let item = null;
                  this.smsList.forEach(sms=>{
                    if(sms.thirdTemplateId == data.smsJson.tempId){
                      // this.smsInfo = sms;
                      item = sms;
                    }
                  })
                  // 默认选中
                  this.ruleForm.smsSelect = item.id

                  this.onChange(item.id);



                  this.$nextTick(()=>{
                    //设置输入框值
                    for(var i=0;i<this.smsParams.length;i++){
                      var key = this.smsParams[i];
                      document.getElementById(key).value = data.smsJson.params[key];
                    }
                  })
                }
                if(reachType.indexOf("3") != -1){
                  //回显邮件
                  this.checkList.push("邮件")
                  let item = null;
                  this.emailList.forEach(email=>{
                    if(email.thirdTemplateId == data.mailJson.tempId){
                      // this.smsInfo = sms;
                      item = email;
                    }
                  })
                  // 默认选中
                  this.ruleForm.emailSelect = item.id

                  this.templateSelectMail(item.id);
                  this.sendCouponDataForm.mailJson = data.mailJson;
                  // this.sendCouponDataForm.mailJson.
                }
            }
          }
        })
    },
    /**
     * 新增模版跳转
     */
    addTemplateLink(){
      let that = this;
      this.$confirm("打开新页面时将刷新本页面，并清空本次编辑的数据，请先将流程保存为草稿", "提示", {
        type: "warning",
        closeOnClickModal: false,
      })
        .then(() => {
          that.$router.push({path:"/pages/TemplateManagement/TemplateManagement"});
        })
    },
  },

  mounted() {
    this.getCouponList();
    this.tTempalteListAll();

  },
  watch:{
    checkList: function(){
      if(this.checkList.indexOf("短信") == -1){
        this.$refs.tabs.$children[0].$refs.tabs[0].style.display = 'none';
        this.activeName = '1'
      }else{
        this.$refs.tabs.$children[0].$refs.tabs[0].style.display = 'inline-block';
        this.activeName = '0'
      }
      if(this.checkList.indexOf("邮件") == -1){
        this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'none';
        this.activeName = '0'
      }else{
        this.$refs.tabs.$children[0].$refs.tabs[1].style.display = 'inline-block';
        this.activeName = '1'
      }
    }
  },
  created() {
  },
};
</script>
<style lang="scss" scoped>
.stepset {
  ul {
    width: 460px;
  }
  .flex {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
.el-checkbox {
  margin-right: 30px;
}
/deep/ .el-form {
  .txt {
    /deep/ .el-form-item {
      margin-top: 0px;
    }
    .flex {
      line-height: 3;
      padding: 15px;
      border: 1px solid #999999;
      border-radius: 4px;
    }
    .el-textarea {
      width: auto;
    }
  }
  .phone {
    .el-form-item__content {
      display: flex;
      justify-content: flex-start;
    }
  }
  .textareaParm{
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    outline: 0;
    padding: 0 15px;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  .buttonParm{
    padding: 0 16px !important;
    border-radius: 4px;
    height: 32px !important;
    line-height: 32px !important;
    font-size: 14px !important;
    background: #FFF;
    border: 1px solid #DCDFE6;
    color: #606266;
    background: #66b1ff;
    border-color: #66b1ff;
    color: #FFF;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
  }
}


.font20{
  font-size: 20px !important;
}
/deep/ .w194{
  width: 194px !important;
  .el-input__inner{
    width: 194px  !important;
  }
}
.noMarginRight{
  margin-right: 0 !important;
}
.labelMarginLeft5{
  /deep/ .el-form-item__label{
    margin-left: 10px;
  }
}
/deep/ .w495{
  width: 495px !important;
  .el-input__inner{
    width:495px !important;
  }
}
/deep/ .w605{
  width: 605px !important;
  .el-input__inner{
    width:605px !important;
  }
}
.noMarginLeft{
  margin-left: 0 !important;
}
/deep/ .copyBtn{
  border: 1px solid #0079DC !important;
  border-radius: 16px !important;
  background-color: #409EFF !important;
  color: #fff !important;
}
.mr10{
  margin-right: 10px !important;
}
.desc{
  color: #c4c4c4;
  font-size: 14px;
}
.w706{
  width: 706px !important;
}
.w738{
  width: 738px !important;
}
.h40{
  height: 40px !important;
}
.lh40{
  line-height: 40px !important;
}</style>

